package com.lib.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.widget.Toast;

import com.qbw.encryption.*;
import com.qbw.log.XLog;

import java.io.File;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @author qbw
 * @createtime 2016/04/15 11:33
 */


public class AppUtil {

    /**
     * @return 程序版本号
     */
    public static int getVersionCode(Context context) {
        int vercode = 0;
        try {
            PackageInfo packageInfo = context.getPackageManager()
                                             .getPackageInfo(context.getPackageName(), 0);
            vercode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return vercode;
    }

    /**
     * @return 程序版本名
     */
    public static String getVersionName(Context context) {
        String vername = "";
        try {
            PackageInfo packageInfo = context.getPackageManager()
                                             .getPackageInfo(context.getPackageName(), 0);
            vername = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return vername;
    }

    /**
     * @return meta配置
     */
    public static String getMetaData(Context context, String name) {
        String value = "";
        try {
            ApplicationInfo applicationInfo = context.getPackageManager()
                                                     .getApplicationInfo(context.getPackageName(),
                                                                         PackageManager.GET_META_DATA);
            value = applicationInfo.metaData.getString(name);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * @return 证书MD5签名
     */
    public static String getCertSignature(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                                             .getPackageInfo(context.getPackageName(),
                                                             PackageManager.GET_SIGNATURES);
            Signature[] signs = packageInfo.signatures;
            Signature sign = signs[0];
            return MD5Util.encryptHex(sign.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            XLog.e(e);
        }
        return "";
    }

    public static String getLanguage() {
        Locale locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = Resources.getSystem().getConfiguration().getLocales().get(0);
        } else {
            //noinspection deprecation
            locale = Resources.getSystem().getConfiguration().locale;
        }
        return locale.getLanguage() + "-" + locale.getCountry();
    }

    public static String getTimezone() {
        Calendar calendar = Calendar.getInstance();
        TimeZone zone = calendar.getTimeZone();
        return zone.getID();
    }

    public static void shareAppShop(Context context, String packageName, String toastWhenFailed) {
        try {
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, toastWhenFailed, Toast.LENGTH_SHORT).show();
        }
    }

    public static void openApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = FileProvider.getUriForFile(context,
                                             "com.gosuncnwelink.twowheels.fileprovider",
                                             file);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);
    }

    public static boolean isNavigationBarShow(Activity context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = context.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(context).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if (menu || back) {
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * 分享文字内容
     *
     * @param dlgTitle 分享对话框标题
     * @param subject  主题
     * @param content  分享内容（文字）
     */
    public static void shareText(Context context, String dlgTitle, String subject, String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setType("text/plain");
        if (TextUtils.isEmpty(subject)) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }

        intent.putExtra(Intent.EXTRA_TEXT, content);

        // 设置弹出框标题
        if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题
            context.startActivity(Intent.createChooser(intent, dlgTitle));
        } else { // 系统默认标题
            context.startActivity(intent);
        }
    }

    public static boolean isEnableNotification(Context context) {
        NotificationManagerCompat manager = NotificationManagerCompat.from(context);
        return manager.areNotificationsEnabled();
    }

    public static void goNotificationSet(Activity activity) {
        try {

            /*if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Intent intent = new Intent();
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                intent.putExtra("app_package", activity.getApplication().getPackageName());
                intent.putExtra("app_uid", activity.getApplicationInfo().uid);
                activity.startActivity(intent);
            } else {*/
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", activity.getApplication().getPackageName(), null);
            intent.setData(uri);
            activity.startActivity(intent);
            //}
        } catch (Exception e) {
            e.printStackTrace();
            XLog.e(e);
        }
    }
}
